<template>
  <div class="app-container">
    <!-- <el-card
      :bordered="false"
      shadow="never"
      class="ivu-mb-16"
      :body-style="{ padding: 0 }"
    > -->
    <div class="filter-container">
      <el-form
        ref="formValidate"
        :model="formValidate"
        @submit.native.prevent
        inline
      >
        <!-- <el-form-item label="状态：" label-for="status">
            <el-select
              v-model="formValidate.status"
              placeholder="请选择"
              @change="userSearchs"
              clearable
              class="form_content_width"
            >
              <el-option value="1" label="显示"></el-option>
              <el-option value="0" label="不显示"></el-option>
            </el-select>
          </el-form-item> -->
        <el-form-item label="身份昵称：" label-for="roleName">
          <el-input
            clearable
            placeholder="请输入身份昵称"
            v-model="formValidate.roleName"
            class="form_content_width"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="userSearchs">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- </el-card> -->
    <el-card :bordered="false" shadow="never" v-loading="spinShow">
      <el-button type="primary" @click="add('添加')">添加角色 </el-button>
      <el-table
        :data="tableList"
        ref="table"
        class="mt14"
        v-loading="loading"
        highlight-current-row
        no-userFrom-text="暂无数据"
        no-filtered-userFrom-text="暂无筛选结果"
      >
        <el-table-column label="ID" min-width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="身份昵称" min-width="130">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="权限" min-width="1000">
            <template slot-scope="scope">
              <span class="line1">{{ scope.row.rules }}</span>
            </template>
          </el-table-column> -->
        <!-- <el-table-column label="状态" min-width="120">
          <template slot-scope="scope">
            <el-switch
              class="defineSwitch"
              :active-value="true"
              :inactive-value="false"
              v-model="scope.row.status"
              :value="scope.row.status"
              @change="onchangeIsShow(scope.row)"
              size="large"
              active-text="显示"
              inactive-text="隐藏"
            >
            </el-switch>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" fixed="right" width="120">
          <template slot-scope="scope">
            <a @click="edit(scope.row, '编辑')">编辑</a>
            <el-divider direction="vertical"></el-divider>
            <a @click="del(scope.row, '删除', scope.$index)">删除</a>
          </template>
        </el-table-column>
      </el-table>
      <div class="acea-row row-right page">
        <pagination
          v-if="total"
          :total="total"
          :page.sync="formValidate.pageNum"
          :pageSize.sync="formValidate.pageSize"
          @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 新增编辑-->
    <el-dialog
      :visible.sync="modals"
      :title="`${modelTit}角色`"
      :close-on-click-modal="false"
      :show-close="true"
      width="540px"
      @closed="closed"
    >
      <el-form
        ref="formInline"
        :model="formInline"
        :rules="ruleValidate"
        label-width="100px"
        @submit.native.prevent
      >
        <el-form-item label="角色名称：" label-for="roleName" prop="roleName">
          <el-input
            placeholder="请输入身份昵称"
            v-model="formInline.roleName"
          />
        </el-form-item>
        <!-- <el-form-item label="是否开启：" prop="status">
          <el-radio-group v-model="formInline.status">
            <el-radio :label="true">开启</el-radio>
            <el-radio :label="false">关闭</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="权限：">
          <div class="trees-coadd">
            <div class="scollhide">
              <div class="iconlist">
                <el-tree
                  :data="menusList"
                  show-checkbox
                  node-key="id"
                  ref="tree"
                  :default-checked-keys="selectIds"
                  :props="defaultProps"
                >
                </el-tree>
                <!-- <el-tree
                  :data="menusList"
                  node-key="id"
                  check-strictly
                  show-checkbox
                  highlight-current
                  ref="tree"
                  :props="defaultProps"
                  @check-change="handleCheckChange"
                ></el-tree> -->
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onCancel">取 消</el-button>
        <el-button type="primary" @click="handleSubmit('formInline')"
          >提 交</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
  <script>
import { mapState } from "vuex";
import {
  roleListApi,
  roleSetStatusApi,
  menusListApi,
  roleCreateApi,
  roleInfoApi,
  roleUpdateApi,
  addSysRole,
  updateSysRole,
  deleteData,
  editTree
} from "@/api/setting";
import { isNumber } from "lodash";

import menusRouter from "@/router/modules/menus";

export default {
  name: "systemrRole",
  data() {
    return {
      menuListIds:[],
      spinShow: false,
      modals: false,
      total: 0,
      grid: {
        xl: 7,
        lg: 7,
        md: 12,
        sm: 24,
        xs: 24,
      },
      loading: false,
      formValidate: {
        // status: "",
        // roleName: "",
        pageNum: 1,
        pageSize: 20,
      },
      tableList: [],
      formInline: {
        roleName: "",
        // status: 0,
        menuIds: [],
        id: 0,
        rules: "",
      },
      menusList: [],
      selectIds: [],
      modelTit: "",
      ruleValidate: {
        roleName: [
          { required: true, message: "请输入角色昵称", trigger: "blur" },
        ],
        // status: [
        //   { required: true, message: "请选择是否开启", trigger: "change" },
        // ],
        // menuIds: [
        //     { required: true, validator: validateStatus, trigger: 'change' }
        // ]
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  computed: {
    ...mapState({
      permissionMenuListDatas: (state) => state.user.permissionMenuListDatas,
    }),
  },
  created() {
    this.getList();
    // this.getRolesPermissionList();
  },
  mounted() {
    console.log(888, this.permissionMenuListDatas);
  },
  methods: {
    getCheckedKeys() {
      console.log(this.$refs.tree.getCheckedKeys());
    },
    closed() {
      this.formInline = {
        roleName: "",
        status: 0,
        menuIds: [],
        id: 0,
      };
      this.selectIds = [];
      this.menusList = [];
    },
    // 添加
    add(name) {
      this.modelTit = name;
      this.modals = true;
      this.getmenusList();
    },
    // 删除
    del(row, tit, num) {
      deleteData(row.id).then((response) => {
        this.listLoading = true;
        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 1000);
        this.getList();
      });
    },
    // 修改是否显示
    onchangeIsShow(row) {
      let data = {
        id: row.id,
        status: row.status,
      };
      roleSetStatusApi(data)
        .then(async (res) => {
          this.$message.success(res.message);
        })
        .catch((res) => {
          this.$message.error(res.message);
        });
    },
    //获取角色权限菜单列表
    // getRolesPermissionList(){
    //   this.loading = true;
    //   // this.formValidate.status = this.formValidate.status || "";
    //   roleListApi(this.formValidate)
    //     .then(async (res) => {
    //       let data = res.data;
    //       this.tableList = data;
    //       this.total = res.data.total;
    //       this.loading = false;
    //     })
    //     .catch((res) => {
    //       this.loading = false;
    //       this.$message.error(res.msg);
    //     });
    // },
    // 列表
    getList() {
      this.loading = true;
      // this.formValidate.status = this.formValidate.status || "";
      roleListApi(this.formValidate)
        .then(async (res) => {
          let data = res.data;
          this.tableList = data.records;
          this.total = res.data.records.total;
          this.loading = false;
        })
        .catch((res) => {
          this.loading = false;
          this.$message.error(res.msg);
        });
    },
    // 表格搜索
    userSearchs() {
      this.formValidate.pageNum = 1;
      this.getList();
    },

    // traverseTreeIdDFS(node) {
    //   node.forEach((node) => {
    //     // 处理当前节点，例如打印或进一步操作
    //     // 如果节点有子节点，递归处理它们
    //     if (node.children) {
    //       this.traverseTreeIdDFS(node.children);
    //     }
    //     this.selectIds.push(node.id);
    //   });
    // },
    // 编辑
    async edit(row, name) {
      this.selectIds = [];
      this.getmenusList();

      this.modelTit = name;
      this.formInline.id = row.id;
      this.formInline.roleName = row.name;

      this.modals = true;
      this.rows = row;
      // this.getInfo(row);


      

      editTree(row.id)
        .then(async (res) => {
          let data = res.data;
           this.selectIds =
           this.extractIds( data.menuList);
           console.log(999,this.selectIds );
          // this.traverseTreeIdDFS(data.menuList);
        })
        .catch((res) => {
          this.$message.error(res.msg);
        });
    },

    // 递归提取所有 id
 extractIds(nodes, result = []) {
  nodes.forEach(node => {
    result.push(node.id);
    if (node.children) {
      extractIds(node.children, result);
    }
  });
  return result;
},
    // 菜单列表
    getmenusList() {
      this.menusList = [];
      this.menusList = menusRouter;

      // this.spinShow = true;
    },
    // 详情
    getInfo(row) {
      let data = row;
      this.formInline.id = data.id;
      this.formInline.roleName = data.name;
      // this.menuIds = data.menuList;

      // this.spinShow = true;
      // roleInfoApi(row.id)
      //   .then(async (res) => {
      //     let data = res.data;
      //     this.formInline.id = data.id;
      //     this.formInline.roleName = data.roleName;
      //     this.formInline.status = data.status;
      //     this.selectIds = data.ids || [];
      //     this.menusList = data.menus;
      //     this.spinShow = false;
      //   })
      //   .catch((res) => {
      //     this.spinShow = false;
      //     this.$message.error(res.msg);
      //   });
    },
    // forChildrenChecked(arr, status, pid) {
    //   if (arr.length) {
    //     let len = arr.length;
    //     for (var j = 0; j < len; j++) {
    //       var childNode = this.$refs.tree.getNode(arr[j].id).data;
    //       if (status) {
    //         this.$refs.tree.setChecked(childNode.id, true);
    //         childNode.checked = true;
    //       }
    //       if (!status) {
    //         this.$refs.tree.setChecked(childNode.id, false);
    //         childNode.checked = false;
    //       }
    //       if (childNode.children.length) {
    //         this.forChildrenChecked(childNode.children, status);
    //       }
    //     }
    //   }
    // },

    // clickDeal(currentObj, treeStatus, ccc) {
    //   // 用于：父子节点严格互不关联时，父节点勾选变化时通知子节点同步变化，实现单向关联。
    //   let selected = treeStatus.checkedKeys.indexOf(currentObj.id); // -1未选中
    //   // 选中
    //   if (selected !== -1) {
    //     // 子节点只要被选中父节点就被选中
    //     this.selectedParent(currentObj);
    //     // 统一处理子节点为相同的勾选状态
    //     this.uniteChildSame(currentObj, true);
    //   } else {
    //     // 未选中 处理子节点全部未选中
    //     if (currentObj.children.length !== 0) {
    //       this.uniteChildSame(currentObj, false);
    //     }
    //     let selParent = false;
    //     let parentNode = currentObj.pid
    //       ? this.$refs.tree.getNode(currentObj.pid).data
    //       : undefined;
    //     if (parentNode && parentNode.children.length) {
    //       for (let i = 0; i < parentNode.children.length; i++) {
    //         if (treeStatus.checkedKeys.includes(parentNode.children[i].id)) {
    //           selParent = true;
    //         }
    //       }
    //     }
    //     if (!selParent && currentObj.pid)
    //       this.$refs.tree.setChecked(currentObj.pid, false);
    //   }
    // },
    // // 统一处理子节点为相同的勾选状态
    // uniteChildSame(treeList, isSelected) {
    //   this.$refs.tree.setChecked(treeList.id, isSelected);
    //   for (let i = 0; i < treeList.children.length; i++) {
    //     this.uniteChildSame(treeList.children[i], isSelected);
    //   }
    // },
    // // 统一处理父节点为选中
    // selectedParent(currentObj) {
    //   ;
    //   let currentNode = this.$refs.tree.getNode(currentObj);
    //   if (currentNode.parent !== undefined) {
    //     this.$refs.tree.setChecked(currentNode.parent, true);
    //     this.selectedParent(currentNode.parent);
    //   }
    // },
    // tidyRes(menus) {
    //   let data = [];
    //   menus.map((menu) => {
    //     if (menu.title === "主页") {
    //       menu.checked = true;
    //       // menu.disabled = true;
    //       if (menu.children.length) {
    //         menu.children.map((v) => {
    //           v.checked = true;
    //         });
    //       }
    //       data.push(menu);
    //     } else {
    //       data.push(this.initMenu(menu));
    //     }
    //   });
    //   this.$set(this, "menusList", data);
    // },
    initMenu(menu) {
      let data = {},
        checkMenus = "," + this.formInline.menuIds + ",";
      data.title = menu.title;
      data.id = menu.id;
      data.pid = menu.pid;
      data.children = menu.children;
      data.checked = menu.checked;

      if (menu.children && menu.children.length > 0) {
        data.children = [];
        menu.children.map((child) => {
          data.children.push(this.initMenu(child));
        });
      } else {
        data.checked = checkMenus.indexOf(String("," + data.id + ",")) !== -1;
        data.expand = !data.checked;
      }
      return data;
    },
    // 提交
    handleSubmit(name) {
      this.$refs[name].validate(async (valid) => {
        if (valid) {
          this.formInline.menuIds = [...this.$refs.tree.getCheckedKeys()];
          if (this.formInline.menuIds.length === 0)
            return this.$message.warning("请至少选择一个权限");
          // 修改时需加一个ID字段
          let data = {
            name: this.formInline.roleName,
            menuIds: this.formInline.menuIds,
            // roleName: this.formInline.roleName,
            // status: this.formInline.status,
            // rules: this.formInline.menuIds.join(","),
          };
          let res;
          try {
            if (this.modelTit === "添加") {
              res = await addSysRole(data);
            } else {
              data.id=this.formInline.id
              res = await updateSysRole(data);
            }
            // res = await updateSysRole(data)

            // if (isNumber(this.formInline.id)) {
            //   data.id = this.formInline.id;
            //   res = await addSysRole(data);
            // } else {
            //   res = await roleCreateApi(data);
            // }
            this.$message.success(res.msg);
            this.modals = false;
            this.getList();
            this.$refs[name].resetFields();
            this.formInline.menuIds = [];
          } catch (err) {
            this.$message.error(err.msg);
          }
        } else {
          return false;
        }
      });
    },
    onCancel() {
      this.spinShow = false;

      this.$refs["formInline"].resetFields();
      this.formInline.menuIds = [];
      this.selectIds = [];
      this.modals = false;
      this.menusList = [];
    },
  },
};
</script>
  
<style lang="scss" scoped>
.trees-coadd {
  width: 100%;
  height: 385px;

  .scollhide {
    width: 100%;
    height: 100%;
    overflow-x: hidden;
    overflow-y: scroll;
    // margin-left: 18px;
  }

  .scollhide::-webkit-scrollbar {
    display: none;
  }
}
</style>
  